//
//  asio_connection_handler.hpp
//  Amqp_test
//
//  Created by HNXF on 2022/7/26.
//

#ifndef asio_connection_handler_hpp
#define asio_connection_handler_hpp

#include <boost/asio.hpp>
#include <amqpcpp.h>
#include <vector>
#include <memory>

constexpr size_t input_buffer_size_ = 4 * 1024; //4kb

class amqp_buffer;
class asio_connection_handler : public AMQP::ConnectionHandler
{
    
public:
    asio_connection_handler(boost::asio::io_service& io_service,
                            const std::string& host,
                            uint16_t port);
    ~asio_connection_handler();
    
    asio_connection_handler(const asio_connection_handler&) = delete;
    asio_connection_handler& operator=(const asio_connection_handler&) = delete;
    
private:
    void do_connect(const std::string& host, uint16_t port);
    void connect_handler(const boost::system::error_code & ec);
    
    void onData(AMQP::Connection* connection, const char* data, size_t size) override;
    void onError(AMQP::Connection* connection, const char* message) override;
    void onClosed(AMQP::Connection* connection) override;
    
    void on_network_error(boost::system::error_code error, const std::string& source);
    
    void do_read();
    void do_write();
    void handle_data();
       
private:
    boost::asio::io_service& io_service_;
    boost::asio::ip::tcp::socket socket_;
    boost::asio::deadline_timer timer_;
    
    std::vector<char> input_buffer_;
    std::shared_ptr<amqp_buffer> amqp_buffer_;
    AMQP::Connection* connection_ptr_;
    std::deque<std::vector<char>> output_buffer_;
    
    bool is_connected_;
    bool is_writing_;
    bool should_quit_;
};

#endif /* asio_connection_handler_hpp */
